import React, { Component } from 'react'
import { Button, View } from 'react-native'
import { InputItem, List, WhiteSpace } from 'antd-mobile'
import { get } from 'lodash'

import { variables } from '../styles'

export class Entity extends Component {
  state = { modified: {} }

  modify = key => value => {
    if (key.includes('.')) throw new Error('unsupported nested modifying')
    const pv = get(this.props.data, key)
    const nv = pv == undefined ? value : pv.constructor(value)
    this.setState({ modified: { ...this.state.modified, [key]: nv } })
  }

  render = () =>
    (({ data, schema, loading, editing, onSubmit, onDelete }, { modified }) =>
      !loading && (
        <View>
          <WhiteSpace />
          <List>
            {schema.map(
              ({ key, label, editable, render, ...props }, index) =>
                !label ? (
                  <WhiteSpace
                    key={index}
                    style={{
                      borderColor: variables.border_color_base,
                      borderWidth: variables.border_width_sm / 3,
                      backgroundColor: variables.fill_body,
                    }}
                  />
                ) : (
                  (({ Item, value }) => (
                    <Item
                      key={key}
                      value={value}
                      extra={!(editing && editable) && value}
                      children={label}
                      placeholder={`Input ${label}`}
                      onChange={this.modify(key)}
                      {...props}
                    />
                  ))({
                    Item: editing && editable ? InputItem : List.Item,
                    value: (render || un(String))(
                      get(modified, key) || get(data, key),
                    ),
                  })
                ),
            )}
          </List>
          {editing && (
            <View>
              <WhiteSpace />
              {onSubmit && (
                <WhiteButton
                  title="Save"
                  onPress={() => onSubmit({ ...data, ...modified })}
                />
              )}
              <WhiteSpace />
              {onDelete && (
                <WhiteButton
                  color="red"
                  title="Delete"
                  onPress={() => onDelete(data)}
                />
              )}
            </View>
          )}
        </View>
      ))(this.props, this.state)
}

const WhiteButton = props => (
  <View style={{ backgroundColor: 'white' }}>
    <Button {...props} />
  </View>
)

const un = f => x => (x == undefined ? undefined : f(x))
